from service import RoleManageService
from util.Service import *
from util.PwdUtil import createHashPwd
# 查询所有用户信息（分页）
def getUserAll(page:Page = Page(),cdn:dict = dict()):
    Users = User.getAllUser(page,cdn)
    return Users

# 根据用户id查询用户信息
def getUserInfo(id):
    user = User.getUserById(id)
    rids = User.getUserRoles(id) 
    roles = Role.getRolesInId(rids)
    return {
        'user':user,
        'roles':roles
    }
# 根据用户的uid 和 rid 查询用户拥有的菜单
def getUserMenusByUidAndRid(uid:int,rid:int):
    if(User.hasUserRole(uid,rid)):
        return RoleManageService.getMenusByRId(rid)
    return []
    
# 根据用户的uid 和 rid 查询用户的所有菜单按钮
def getUserMenuHandle(uid:int,rid:int):
    if(User.hasUserRole(uid,rid)):
        return RoleManageService.getMenuHandles(rid)
    return []

# 根据用户id查询用户状态
def getUserStatus(uid):
    r = User.getUserById(uid)
    if(r!=None):
        return r['status']

# 添加用户
def addUser(data:dict):
    username = data['username']
    if User.hasUserByUsername(username):
        return 2
    if len(username) < 8:
        return 3
    pwd = createHashPwd(username,data['password'])
    data['password'] = pwd
    data = formatParam(data,['uId'])
    data['initTime'] = datetime.utcnow()
    data['status'] = '1'
    data['sex'] = '0'
    data['head'] = 'User'
    User.addUser(data)
    return True

# 修改用户信息(nickname,sex,head...)
def updateUser(data:dict):
    uid = data['uId']
    data = formatParam(data,['uId','username','password','initTime'])
    User.updateById(uid,data)
    return True


# 修改用户密码
def resetPwd(id:int,pwd:str):
    if id == 1 :
        return False
    user = User.getUserById(id)
    if user == None:
        return False
    User.updateById(id,{'password':createHashPwd(user['username'],pwd)})
    return True

# 用户修改密码
def updatePwd(id:int,d:dict):
    user = User.getUserById(id,True)
    if user == None:
        return False
    username = user['username']
    old = d['oPwd']
    nPwd = d['pwd']
    # 判断是否与原密码相等
    oldPwdHash = createHashPwd(username,old)
    if(oldPwdHash != user['password']):
        return 2
    if len(nPwd) < 8:
        return 3
    User.updateById(id,{'password':createHashPwd(username,nPwd)})
    return True

#删除用户
def delUser(uids:list[int]):
    # 在用户角色映射表中删除 mid 的映射关系
    database.transaction()
    try:
        with database.atomic():
            if(1 in uids):
                return False
            User.delUserRoleInUid(uids)
            User.delUserStatusInUid(uids)
            User.delUserById(uids)
            database.commit()
    except:
        database.rollback()
        return False
    return True


# 查看用户拥有的角色
def getUserRoles(uid):
    rids = User.getUserRoles(uid)
    roles = Role.getRolesInId(rids)
    return {'roles':roles }

# 查看用户拥有的角色的名字
def getUserRolesName(uid):
    rids = User.getUserRoles(uid)
    roles = Role.getRoleNameInIsd(rids)
    return roles



# 添加用户的角色
def uploadUserRoles(uid,rids):
    if uid == 1:
        return False
    canAddRids = list()
    notAddRids = list()
    try:
        database.begin()
        User.delUserRoleInUid([uid])
        for rid in rids:
            if Role.hasRole(rid) and not User.hasUserRole(uid,rid):
                canAddRids.append(rid)
            else:
                notAddRids.append(rid)
        User.addUserRole(uid,canAddRids)
        database.commit()
        return True
    except:
        database.rollback()
        return False

# 启用和禁用某用户
def userUpdateStatus(id,k):
    return User.userUpdateStatus(id,k)

# 上传用户头像
def userUpdateHead(uid,filepath):
    return User.userUpdateHead(uid,filepath)